
import store from '../store';
function commonFetch(url,options,method='get',success,error){    
  var initObj="",init;
    for(var key in options){    
      initObj=initObj+key+"="+options[key]+"&";
    }  
    initObj=initObj.substr(0,initObj.length-1);
    console.log("请求参数："+initObj);  
    if(method=="POST" || method=="PUT"){     
      init={
        method:method, 
        mode:"cors",             
        headers:new Headers({
          "REQ-TYPE": "API",
          "Authorization":'Bearer ' + store.state.token,
          'content-type':"application/x-www-form-urlencoded"
        }),
          body:initObj
        };
    }else{
      url=url+"?"+initObj;
      init={
        method:method,
        mode:"cors",  
        headers:new Headers({
          "REQ-TYPE": "API",
          "Authorization":'Bearer ' + store.state.token,
          'content-type':"application/x-www-form-urlencoded"
         }),          
        };
    }
   window.fetch(url,init).then(function(response) {
    return response.json();

  }).then(function(json) {
    console.log('parsed json', json);
    success(json);
  }).catch(function(ex) {
    console.log('parsing failed', ex);
    error(ex);
  })
}

/**
 * GET请求
 * @param url 请求地址
 * @param options 请求参数
 */
function GET(url, options,success,err) {
    return commonFetch(url, options, 'GET',success,err)
  }

  /**
   * POST请求
   * @param url 请求地址
   * @param options 请求参数
   */
function POST(url, options,success,err) {
    return commonFetch(url, options, 'POST',success,err)
  }
  function DELETE(url, options,success,err) {
    return commonFetch(url, options, 'DELETE',success,err)
  }
  function PUT(url, options,success,err) {
    return commonFetch(url, options, 'PUT',success,err)
  }
  window.GET=GET;
  window.POST=POST;
  window.DELETE=DELETE;
  window.PUT=PUT;
  
  export {GET,POST,DELETE,PUT};